
from xml.dom import minidom as xml
from xml.dom.minidom import Node

def parseFile(path):
    with open(path, "r") as f:
        doc = xml.parse(f)
        return XmlNodeWrapper(doc)

class XmlNodeWrapper:
    __slots__ = ("node")

    def __init__(self, node):
        self.node = node

    def getTextNode(self):
        for child in self.node.childNodes:
            if child.nodeType == Node.TEXT_NODE:
                return child
        raise KeyError("Text node was not found")

    def getText(self):
        for child in self.node.childNodes:
            if child.nodeType == Node.TEXT_NODE:
                return child.data
        raise KeyError("Text node was not found")

    def setText(self, value):
        for child in self.node.childNodes:
            if child.nodeType == Node.TEXT_NODE:
                child.data = value
                return
        raise KeyError("Text node was not found") # TODO: create text node

    def getChild(self, tagName):
        for child in self.node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE and child.tagName == tagName:
                return XmlNodeWrapper(child)
        raise KeyError("Node with tag '%s' was not found" % tagName)

    def getAllChilds(self, tagName):
        for child in self.node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE and child.tagName == tagName:
                yield XmlNodeWrapper(child)

    def getValue(self, tagName):
        child = self.getChild(tagName)
        return child.getText()

    def getElementsByTagName(self, tagName):
        for elem in self.node.getElementsByTagName(tagName):
            yield XmlNodeWrapper(elem)

    def writeXml(self, file):
        self.node.writexml(file)